import React, { useState, useEffect, useContext } from "react";
export default function TimerHook() {
    const [count1, reset1, toggle1] = useCounter(10);
    const [count2, reset2, toggle2] = useCounter(100);

    return (
        <div>
            <button onClick={reset1} >reset1</button>
            <button onClick={reset2}>reset2</button><br />
            <button onClick={toggle1}>Pause/Start1</button>
            <button onClick={toggle2}>Pause/Start2</button>
            <br />
            TimerHook:<strong>{count1}</strong><br />
            TimerHook:<strong>{count2}</strong><br />
        </div>)
}

//自定义Timer
function useCounter(initialCount) {
    const [count, setCount] = useState(initialCount);
    const [pasue, setPasue] = useState(false);
    useEffect(() => {

        const timer = setTimeout(() => !pasue && setCount(count + 1), 1000);
        return () => clearTimeout(timer);
    }, [count, pasue]);

    const reset = () => {
        setCount(initialCount);
    }
    const toggle = () => {
        setPasue(!pasue);
    }
    return [count, reset, toggle];
}

